package com.example.management.system.service.impl

import com.example.management.system.domain.UserDO
import com.example.management.system.domain.UserOnline
import com.example.management.system.service.SessionService

import org.apache.shiro.session.Session
import org.apache.shiro.session.mgt.eis.SessionDAO
import org.apache.shiro.subject.SimplePrincipalCollection
import org.apache.shiro.subject.support.DefaultSubjectContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

import java.util.ArrayList

/**
 * 待完善
 *
 * @author bootdo
 */
@Service
class SessionServiceImpl @Autowired
constructor(private val sessionDAO: SessionDAO) : SessionService {

    override fun list(): List<UserOnline> {
        val list = ArrayList<UserOnline>()
        val sessions = sessionDAO.activeSessions
        for (session in sessions) {
            val userOnline = UserOnline()
            if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
                continue
            } else {
                val principalCollection = session
                        .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) as SimplePrincipalCollection
                val userDO = principalCollection.primaryPrincipal as UserDO
                userOnline.username=(userDO.username)
            }
            userOnline.id =(session.id as String)
            userOnline.host = (session.host)
            userOnline.startTimestamp = (session.startTimestamp)
            userOnline.lastAccessTime = (session.lastAccessTime)
            userOnline.timeout =(session.timeout)
            list.add(userOnline)
        }
        return list
    }

    override fun listOnlineUser(): List<UserDO> {
        val list = ArrayList<UserDO>()
        var userDO: UserDO
        val sessions = sessionDAO.activeSessions
        for (session in sessions) {
            var principalCollection = SimplePrincipalCollection()
            if (session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) == null) {
                continue
            } else {
                principalCollection = session
                        .getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY) as SimplePrincipalCollection
                userDO = principalCollection.primaryPrincipal as UserDO
                list.add(userDO)
            }
        }
        return list
    }

    override fun sessionList(): Collection<Session> {
        return sessionDAO.activeSessions
    }

    override fun forceLogout(sessionId: String): Boolean {
        val session = sessionDAO.readSession(sessionId)
        session.timeout = 0
        return true
    }
}
